<%@ page import="org.bson.Document" %>
<%@ page import="com.mongodb.client.*" %>
<%@ page import="java.util.regex.Pattern" %>
<%@ page import="org.bson.conversions.Bson" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.LinkedList" %>
<%@ page import="cn.hutool.poi.excel.ExcelWriter" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Mongo-Web学生管理系统</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
<jsp:include page="checkLogin.jsp"></jsp:include>

<jsp:include page="major.jsp"></jsp:include>

<%
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    String url = "mongodb://g08:abc%408@mongo.zhledu.cn:27017/g08";
    MongoClient client = MongoClients.create(url);
    MongoIterable<String> names = client.listDatabaseNames();
    MongoDatabase g08 = client.getDatabase("g08");
    MongoCollection<Document> collection = g08.getCollection("student");
    //查询系统中有多少个专业

   List<Bson> queryList = new LinkedList<>();
    Document group = new Document().append("$group", new Document("_id", "$major"));
    queryList.add(group);
    AggregateIterable<Document> majorList = collection.aggregate(queryList);
    
    Document query = new Document();
    String sno = request.getParameter("sno");
    if (sno != null && sno != "") {
        query.append("sno", Pattern.compile(sno));
    } else {
        sno = "";
    }
    String name = request.getParameter("name");
    if (name != null && name != "") {
        query.append("name", Pattern.compile(name));
    } else {
        name = "";
    }
    String sex = request.getParameter("sex");
    if (sex != null && sex != "") {
        query.append("sex", sex);
    } else {
        sex = "";
    }
    String idCard = request.getParameter("idCard");
    if (idCard != null && idCard != "") {
        query.append("idCard", Pattern.compile(idCard));
    } else {
        idCard = "";
    }
    String major = request.getParameter("major");
    if (major != null && major != "") {
        query.append("major", major);
    } else {
        major = "";
    }
    String action = request.getParameter("action");
    if ("export".equals(action)) {
        response.setHeader("content-disposition", "attachment; filename=student.xlsx");
        final FindIterable<Document> exportList = collection.find(query).sort(new Document("sno", -1));
        ExcelWriter writer = new ExcelWriter();
        writer.addHeaderAlias("_id", "编号");
        writer.addHeaderAlias("sno", "学号");
        writer.addHeaderAlias("name", "姓名");
        writer.addHeaderAlias("sex", "性别");
        writer.addHeaderAlias("age", "年龄");
        writer.addHeaderAlias("birthDay", "出生日期");
        writer.addHeaderAlias("idCard", "身份证号");
        writer.addHeaderAlias("phone", "电话号码");
        writer.addHeaderAlias("major", "专业");
        writer.addHeaderAlias("email", "电子邮件");
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("address", "住址");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.write(exportList);
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream);
        writer.close();
        outputStream.flush();
        outputStream.close();
    }
    int pageSize = 10;
    int pageNum = 1;
    int totalCount = new Long(collection.countDocuments(query)).intValue();
    int totalPageNum = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
    try {
        String _pageNum = request.getParameter("pageNum");
        pageNum = Integer.parseInt(_pageNum);
        if (pageNum <= 1) pageNum = 1;
        if (pageNum >= totalPageNum) pageNum = totalPageNum;
    } catch (Exception e) {
        pageNum = 1;

    }
    final FindIterable<Document> list = collection.find(query).sort(new Document("sno", -1)).skip((pageNum - 1) * pageSize).limit(pageSize);
%>

<div class="container">
    <div class="row" style="background-color: #1e9fff">
        <div class="col-md-6 col-md-offset-4">
            <h1>欢迎使用学生信息管理系统</h1>
        </div>
    </div>

    <div class="row" style="margin-top: 10px">
        <form id="form" action="index.jsp" method="post" class="form-inline">
            <div class="form-group">
                <label>学号:</label>
                <%-- <input type="hidden" name="action" id="action">--%>
                <input id="sno" name="sno" class="form-control" value="<%=sno%>">
            </div>

            <div class="form-group">
                <label> 姓名:</label>
                <input type="hidden" name="pageNum" id="pageNum" value="<%=pageNum%>">
                <input id="name" name="name" class="form-control" value="<%=name%>">
            </div>

            <div class="form-group">
                <label> 身份证号:</label>
                <input id="idCard" name="idCard" class="form-control" value="<%=idCard%>">
            </div>


            <div class="form-group">
                <label> 性别:</label>
                <select id="sex" name="sex" class="form-control">
                    <option class="initSelect" value="">全部</option>
                    <option value="男"  <%=("男".equals(sex) ? "selected" : "")%> >男</option>
                    <option value="女" <%=("女".equals(sex) ? "selected" : "")%>>女</option>
                </select>
            </div>

            <div class="form-group">
                <label> 专业:</label>
                <select id="major" name="major" class="form-control">
                    <option class="initSelect" value="">全部</option>
                    <%
                        for (String m : majorList) {
                    %>
                    <option value="<%=m%>" <%=m.equals(major) ? "selected" : ""%>><%=m%>
                    </option>
                    <%
                        }
                    %>

                </select>
            </div>

            <button type="submit" class="btn btn-info glyphicon glyphicon-search" id="btnSearch">查找</button>
            <button type="reset" class="btn btn-warning glyphicon glyphicon-refresh" id="btnReset">重置</button>
        </form>
    </div>
    <br>
    <div class="row" style="margin-top: 10px;margin-bottom: 10px">
        <div class="btn-group">
            <button id="add" type="button" class="btn btn-info glyphicon glyphicon-plus">添加</button>
            <button id="delMany" type="button" class="btn btn-danger glyphicon glyphicon-remove">删除</button>
            <button id="import" type="button" class="btn btn-success glyphicon glyphicon-import">导入</button>
            <button id="export" type="button" class="btn btn-warning glyphicon glyphicon-export">导出</button>
            <button id="printAll" type="button" class="btn btn-info glyphicon glyphicon-print">打印</button>
            <button id="tongji" type="button" class="btn btn-info glyphicon glyphicon-home">统计分析</button>


        </div>

    </div>

    <table class="table table-bordered table-striped table-hover" style="left: 0">
        <thead>
        <th>
            <input type="checkbox" id="checkAll">全选
        </th>
        <th>学号</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>专业</th>
        <th>身份证号</th>
        <th>手机</th>
        <th>操作</th>
        </thead>
        <%
            for (Document student : list) {
                int id = student.getInteger("_id");
        %>
        <tr>
            <td>
                <input type="checkbox" class="stuId" value="<%=student.getString("sno")%>">
            </td>
            <td><%=student.getString("sno")%>
            </td>
            <td><%=student.getString("name")%>
            </td>
            <td><%=student.getInteger("age")%>
            </td>
            <td><%=student.getString("sex")%>
            </td>
            <td><%=student.getString("major")%>
            </td>
            <td><%=student.getString("idCard")%>
            </td>
            <td><%=student.getString("phone")%>
            </td>
            <td>

                <div class="btn-group">
                    <button type="button"
                            class="btn btn-danger glyphicon glyphicon-remove btn-sm"
                            onclick="deleteOne('<%=student.getString("sno")%>')">删除
                    </button>
                    <button id="view" type="button"
                            class="btn btn-success glyphicon glyphicon-search btn-sm"
                            onclick="view('<%=student.getString("sno")%>')">查看
                    </button>
                    <button id="edit" type="button"
                            class="btn btn-warning glyphicon glyphicon-edit btn-sm"
                            onclick="update('<%=student.getString("sno")%>')">修改
                    </button>
                    <button id="print" type="button" class="btn btn-info glyphicon glyphicon-print btn-sm">打印</button>
                </div>

            </td>
        </tr>

        <%
            }
        %>

        <tr>
            <td colspan="9" style="text-align: right">
                共<%=totalCount%>条记录,共<%=totalPageNum%>页,当前第<%=pageNum%>页
            </td>
        </tr>
    </table>

    <div class="row">
        <ul class="pager">
            <li><a href="javascript:goto('i')">首页</a></li>
            <li><a href="javascript:goto('p')">上一页</a></li>
            <li><a href="#" style="color: red"><%=pageNum%>/<%=totalPageNum%>
            </a></li>
            <li><a href="javascript:goto('n')">下一页</a></li>
            <li><a href="javascript:goto('l')">尾页</a></li>
        </ul>
    </div>

</div>


<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script type="text/javascript">

    $("#import").click(function () {
        window.location.href = "import.jsp";
    });

    $("#checkAll").click(function () {
        $(".stuId").prop("checked", $(this).prop("checked"));
    });

    function goto(index) {
        var _pageNum = $("#pageNum").val();
        var pageNum = 1;
        if (!isNaN(_pageNum)) {
            pageNum = parseInt(_pageNum);
        }
        switch (index) {
            case 'i': {
                $("#pageNum").attr("value", 0);
                break;
            }
            case 'p': {
                $("#pageNum").attr("value", pageNum - 1);
                break;
            }
            case 'n': {
                $("#pageNum").attr("value", pageNum + 1);
                break;
            }
            case 'l': {
                $("#pageNum").attr("value", <%=totalPageNum%>);
                break;
            }
        }
        $("#form").submit();
    }

    function deleteOne(id) {
        swal({
            title: "确认",
            text: "你确定要删除这条记录?删除后无法恢复!",
            icon: "warning",
            buttons: ["我再想想", "不要劝我,非删除不可"],
            dangerMode: true,
        }).then((willDelete) => {
            if (willDelete) {
                window.location.href = "delete.jsp?sno=" + id;
            }
        });
    }

    $("#delMany").click(function () {
        var selectedStudent = $(".stuId:checked");
        var sno = [];
        if (selectedStudent.length > 0) {
            for (var i = 0; i < selectedStudent.length; i++) {
                sno.push($(selectedStudent[i]).val());
            }
            swal({
                title: "确认",
                text: "你确定要删除这些记录?删除后无法恢复!",
                icon: "warning",
                buttons: ["我再想想", "不要劝我,非删除不可"],
                dangerMode: true,
            }).then((willDelete) => {
                if (willDelete) {
                    window.location.href = "delete.jsp?sno=" + sno.join(",");
                }
            });


        } else {
            swal("请至少选择一个学生删除")
        }
    })


    function view(sno) {
        window.location.href = "view.jsp?sno=" + sno;
    }

    function update(sno) {
        window.location.href = "preupdate.jsp?sno=" + sno;
    }


    $("#btnReset").on("click", function () {
        console.log("点击了重置按钮")
        $("#sno").attr("value", "");
        $("#name").attr("value", "");
        $("#idCard").attr("value", "");
        $("[selected]").attr("selected", false);
        $(".initSelect").attr("selected", true);
        $("form").submit();
    });

    $("#add").on("click", function () {
        window.location.href = "add.jsp";
    });

    $("#export").click(function () {
        swal({
            title: "确认",
            text: "你确定要导出查找出来的记录吗!",
            icon: "warning",
            buttons: ["我再想想", "我要导出"],
            dangerMode: true,
        }).then((willDelete) => {
            if (willDelete) {
                $("#form").prop("action", "index.jsp?action=export");
                $("#form").submit();
            }
        });
    });

    $("#printAll").click(function () {
        $("#form").prop("action", "print.jsp");
        $("#form").submit();
    });
    $("#tongji").click(function () {
        window.location.href="tongji.jsp"
    });


</script>

</body>
</html>
